package com.fighYo.edu.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fighYo.servicebase.config.handler.GuliException;
import com.fighYo.edu.entity.EduSubject;
import com.fighYo.edu.entity.SubjectData;
import com.fighYo.edu.service.EduSubjectService;


public class EduSubjectListener extends AnalysisEventListener<SubjectData> {

    EduSubjectService subjectService;

    public EduSubjectListener() {
    }

    public EduSubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }

        EduSubject one = existOneSubject(subjectData.getOneSubjectName());
        if(one == null) {
            one = new EduSubject();
            one.setParentId("0");
            one.setTitle(subjectData.getOneSubjectName());
            subjectService.save(one);
        }

        EduSubject two = existTwoSubject(subjectData.getTwoSubjectName(), one.getId());
        if(two == null) {
            two = new EduSubject();
            two.setParentId(one.getId());
            two.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(two);
        }

    }

    private EduSubject existOneSubject(String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", "0");
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    private EduSubject existTwoSubject(String name, String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name).eq("parent_id", pid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

}
